//
//  PublishViewController.m
//  Accounting
//
//  Created by Billy on 15/8/28.
//  Copyright (c) 2015年 hzqs. All rights reserved.
//

#import "PublishViewController.h"
#import "addImageView.h"
#import <AVFoundation/AVFoundation.h>
#import "lame.h"
#import "Util.h"
//#import <ifaddrs.h>
//#import <arpa/inet.h>
#define kRecordAudioFile @"soundRecord.caf"


@interface PublishViewController () <UITextViewDelegate,AVAudioRecorderDelegate>{
    NSString * type;
}

@property (nonatomic,strong) UITextView *textView;
@property (nonatomic,strong) UIButton *button_addSound; //添加声音
@property (nonatomic,strong)  addImageView *view_addImage; //添加图片

@property (nonatomic,strong) UILabel *label_placeholder;//textview占位符
@property (nonatomic,strong)  UIButton *button_startRecord; //开始录音
@property (nonatomic,strong)  UIButton *button_stopRecord; //停止录音
@property (nonatomic,strong) UIView *view_recorder;  //话筒的view

@property (nonatomic,strong) UIImageView *imageView_record; //话筒的图片

@property (nonatomic,strong) UIView *view_placeButtonToRecord;  //按住录音的view
@property (nonatomic,strong) UIView *view_recordDetails;  //显示多少秒的view

@property (nonatomic,strong) AVAudioRecorder *audioRecorder;//音频录音机
@property (nonatomic,strong) AVAudioPlayer *audioPlayer;//音频播放器，用于播放录音文件

@property (nonatomic,copy) NSString *cafPath; //转换前的caf路径
@property (nonatomic,copy) NSString *strMp3Path; //转换后的mp3路径
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,assign) BOOL flag; //用于标识录音有没有完成

@property (nonatomic,strong)  UIButton *button_release; //发布按钮

@property (nonatomic,strong)  AVAudioSession *sessionPlayBack;
@property (nonatomic,strong) AVAudioSession *sessionRecord;
@end

@implementation PublishViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.flag = NO;
    [self pageSettingsAndSubviewsCreation];
}


#pragma mark - SubviewsCreationAndPageSettings

- (void) pageSettingsAndSubviewsCreation {
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setTitle:@"财务问题"];
    
    
    UIBarButtonItem *barButtonItem_release = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStyleBordered target:self action:@selector(questionPublish)];
    
    [self.navigationItem setRightBarButtonItem:barButtonItem_release];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    
    // textView
    [self.view addSubview:self.textView];
    
    self.label_placeholder = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-20, 30)];
    
    [self.label_placeholder setText:@"问题描述~"];
    [self.label_placeholder setTextColor:[UIColor lightGrayColor]];
    [self.label_placeholder setFont:[UIFont systemFontOfSize:14]];
    [_textView addSubview:self.label_placeholder];

   // 添加图片
    self.view_addImage = [[addImageView alloc]initWithFrame:CGRectMake(5, CGRectGetMaxY(self.textView.frame)+30, SCREEN_WIDTH-10, 75)];
    
    [self.view_addImage.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    [self.view_addImage.layer setBorderWidth:0.5];
    [self.view_addImage.layer setCornerRadius:2.0];
    
    self.view_addImage.itemSpace = (SCREEN_WIDTH - 75*3)/4; //图片间距
    [self.view addSubview:self.view_addImage];
    
    // 添加语音
    
//    self.view_placeButtonToRecord = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view_addImage.frame)+10, SCREEN_WIDTH, 44)];
    
    self.view_placeButtonToRecord = [[UIView alloc] initWithFrame: CGRectMake(0, SCREEN_HEIGHT - 64-40, SCREEN_WIDTH, 40)];
    [self.view addSubview:self.view_placeButtonToRecord];
    [self.view_placeButtonToRecord setBackgroundColor:[Util colorWithHexString:@"3e96ff"]];
    
    self.button_addSound = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    
    [self.button_addSound setTitle:@"按住 录音" forState:UIControlStateNormal];
    [self.button_addSound setTitle:@"松手 结束" forState:UIControlStateHighlighted];
    [self.button_addSound addTarget:self action:@selector(recordStart) forControlEvents:UIControlEventTouchDown];
    [self.button_addSound addTarget:self action:@selector(recordCancel) forControlEvents:UIControlEventTouchDragExit];
    [self.button_addSound addTarget:self action:@selector(recordEnd) forControlEvents:UIControlEventTouchUpInside];
    
    [self.button_addSound setBackgroundColor:[Util colorWithHexString:@"3e96ff"]];
    [self.button_addSound.layer setCornerRadius:4.0];
    [self.view_placeButtonToRecord addSubview:self.button_addSound];
    
    //录音时出现的录音筒
    
    UIView *view_recorder = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2 - 40, SCREEN_HEIGHT/6, 100, 130)];
    self.view_recorder = view_recorder;
    [view_recorder.layer setCornerRadius:2.];
    [view_recorder setBackgroundColor:[UIColor lightGrayColor]];
    
    [self.view_recorder setHidden:YES];
    [self.view addSubview:view_recorder];
    self.view_recorder.alpha = 0.6;
    UIImageView *imageView_record = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 80, 100)];
    self.imageView_record = imageView_record;
    
    [imageView_record setImage:[UIImage imageNamed:@"record_animate_01"]];
    [view_recorder addSubview:imageView_record];
    
    UILabel *label_promt = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView_record.frame), view_recorder.bounds.size.width, 20)];
    [label_promt setText:@"上滑取消"];
    [label_promt setTextAlignment:NSTextAlignmentCenter];
    [label_promt setTextColor:[UIColor whiteColor]];
    [view_recorder addSubview:label_promt];
    

}


- (UITextView *)textView {
    
    if (!_textView) {
        
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(5, 10, SCREEN_WIDTH-10, 100)];
        [_textView.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        [_textView.layer setBorderWidth:1.0];
        [_textView.layer setCornerRadius:2.0];
        [_textView setDelegate:self];
        
        //添加完成键
        
        UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        [topView setBarStyle:UIBarStyleDefault];
        
        UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        
        UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
        
        NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace, doneButton, nil];
        [topView setItems:buttonsArray];
        
        [_textView setInputAccessoryView:topView];
    }
    

    return _textView;
}


#pragma mark - textView delegate

- (void) dismissKeyBoard {
    
    [self.textView resignFirstResponder];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if (![text isEqualToString:@""]) {
        
        [self.label_placeholder setHidden:YES];
    }
    
    if ([text isEqualToString:@""] && range.location == 0 && range.length == 1){
        
        [self.label_placeholder setHidden:NO];
    }
    return YES;
}


#pragma mark - button events handling

- (void) recordStart {

    NSLog(@"开始录音!");
    AVAudioSession *sessionRecord = [AVAudioSession sharedInstance];
    self.sessionRecord = sessionRecord;
    
    NSError *setCategoryError = nil;
    [sessionRecord setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];
    
    if(setCategoryError){
        NSLog(@"111%@", [setCategoryError description]);
    }
    
    [self.view_recorder setHidden:NO];

    if (![self.audioRecorder isRecording]) {
        
        [self.audioRecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
    }
    
    //设置定时检测
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(detectionVoice) userInfo:nil repeats:YES];
}

- (void) recordCancel {
    [self.timer invalidate];
    [self.view_recorder setHidden:YES];
    NSLog(@"取消!");
}
- (void) recordEnd {
    
    [self.view_recorder setHidden:YES]; //消失录音图片
    [self.timer invalidate];
    if ([self.audioRecorder isRecording]) {

        [self.audioRecorder stop];
    }
    NSURL *url=[self getSavePath];
    NSError *error=nil;
    
    if (url) {
        
        self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
        self.audioPlayer.numberOfLoops=0;
        [self.audioPlayer prepareToPlay];

    }

    
    if (error) {
        NSLog(@"创建播放器过程中发生错误，错误信息：%@",error.localizedDescription);
        return;
    }
    
    if ([self.audioPlayer duration] < 0.2) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"时间太短" message:@"请重新录音!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
        return;
    }
    
    //移除旧的语音条
    
    if (self.view_recordDetails) {
        
        [self.view_recordDetails removeFromSuperview];
    }
    [self.view_placeButtonToRecord setHidden:YES];
    
    [self createRecordIconWithTime:[self.audioPlayer duration]];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        //转成mp3
        [self toMp3:kRecordAudioFile];
        
        dispatch_async(dispatch_get_main_queue(), ^{
           
            NSLog(@"转化mp3完成");
        });
    });

}


- (void) createRecordIconWithTime: (NSTimeInterval ) duration {

    UIView *view_recordDetails = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view_addImage.frame)+10, SCREEN_WIDTH, 40)];
    self.view_recordDetails = view_recordDetails;
    [self.view addSubview:view_recordDetails];
    
    //录音内容button
    UIButton *button_recrodContent = [[UIButton alloc] initWithFrame:CGRectMake(5, 0, SCREEN_WIDTH*2/3, 40)];
    [button_recrodContent setBackgroundColor:[Util colorWithHexString:@"#3e96ff"]];
    [button_recrodContent.layer setCornerRadius:4.0];
    [button_recrodContent addTarget:self action:@selector(recordOperation:) forControlEvents:UIControlEventTouchUpInside];
     [button_recrodContent setTag:15];
    [button_recrodContent setShowsTouchWhenHighlighted:YES];
    [view_recordDetails addSubview:button_recrodContent];
    
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(button_recrodContent.bounds.size.width/2, 15, 12, 14)];
    
    [imageView setImage:[UIImage imageNamed:@"laba"]];
    [view_recordDetails addSubview: imageView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) +2.0, 5, 40, 30)];

    [label setTextColor:[UIColor whiteColor]];
    [label setText:[NSString stringWithFormat:@"%.f\''",duration]];
    [label setAdjustsFontSizeToFitWidth:YES];
    [view_recordDetails addSubview:label];
    
    //删除录音内容button
    UIButton *button_delete = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(button_recrodContent.frame), 10, 50, 20)];
    [button_delete addTarget:self action:@selector(recordOperation:) forControlEvents:UIControlEventTouchUpInside];
    
    [button_delete setTitle:@"删除" forState:UIControlStateNormal];
    [button_delete setTitleColor:[Util colorWithHexString:@"3e96ff"] forState:UIControlStateNormal];
    [button_delete setTag:17];
    [view_recordDetails addSubview:button_delete];
    
}

- (void) recordOperation:(UIButton *) button {
    
    switch (button.tag) {
        case 15: //播放
        {
            NSURL *url=[self getSavePath];
            NSError *error=nil;
            //播放准备
            AVAudioSession *sessionPlayBack = [AVAudioSession sharedInstance];
            self.sessionPlayBack = sessionPlayBack;
            NSError *setCategoryError = nil;
            
            [sessionPlayBack setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
            
            
            self.audioPlayer =[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
            [self.audioPlayer setVolume:0.8];
            NSLog(@"url:%@",url);
           
            if (error) {
                NSLog(@"创建播放器过程中发生错误，错误信息：%@",error.localizedDescription);
                return;
            }else {
                
                [self.audioPlayer prepareToPlay];
                [self.audioPlayer play];
            }

        }
            break;
            
            case 17: //删除
        {
            self.flag = NO;

            [button.superview removeFromSuperview];
            [self.view_placeButtonToRecord setHidden:NO];
        }
            break;
            break;
        default:
            break;
    }
    
}


- (void) questionPublish {
    
    //判定有无录音文件
    [self getSavePath]? (self.flag = YES) : (self.flag = NO);
    
    
    
    
    (![self.textView.text isEqualToString:@""])?[self publish]:(self.view_addImage.subviews.count !=1? [self publish]:(self.flag?[self publish]:[self alertMessageShow:@"添加要发布的信息!"]));

    
    
    
    
    
    
    
    
    
}

- (void) alertMessageShow: (NSString *)msg {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil
                          ];
    
    [alert show];
}


- (void) publish{
    
    NSString *content = self.textView.text; //得到文字内容
    NSArray *array_images = self.view_addImage.images;
    // 音频
    NSString *str_mp3 = [NSString stringWithFormat:@"%@/%@",self.strMp3Path,@"record.mp3"];
    NSData *data_mp3 = [NSData dataWithContentsOfFile:str_mp3];
    
    
    if (self.flag == YES&&[self.textView.text isEqualToString:@""]&&self.view_addImage.subviews.count ==1) {
        NSLog(@"有录音---我是1");
        type = @"1";
    }else if (![self.textView.text isEqualToString:@""]&&self.flag == NO&&self.view_addImage.subviews.count ==1){
        
        NSLog(@"有文字---我是2");
       type = @"2";
        
    }else if (self.view_addImage.subviews.count !=1&&self.flag == NO&&[self.textView.text isEqualToString:@""]){
        
        NSLog(@"有图片---我是3");
       type = @"3";
        
    }else if(self.view_addImage.subviews.count ==1&&self.flag == NO&&[self.textView.text isEqualToString:@""]){
        
        NSLog(@"我是空的");
        [self alertMessageShow:@"添加要发布的信息!"];
    }else{
        
        NSLog(@"我有好多---我是4");
       type = @"4";
        
    }

    
    
    NSString *IP = [[NSUserDefaults standardUserDefaults] valueForKey:@"IP"];
    NSDictionary *param4 = @{@"content":content,@"sessionid":@"30",@"Type":type,@"IP":IP};

    
    [[Util shardWebUtil] uploadingMultipleImages:array_images andAudioData:data_mp3 withParameterInServerSide:@"file[]" andOtherParameteres:param4
usingURL:@"http://192.168.0.111/Home/api/uploadImg" succeedBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
    
    NSLog(@"%@",responseObject);
    
    NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
    
    if ([str isEqualToString:@"1"]) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"噢耶，成功啦" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alert setTag:111];
        [alert show];

    } else {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"对不起，你挂啦" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alert show];

    }


    
} failedBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
    
    
}];
    
    
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{
    if (alertView.tag  == 111) {
        
        if (buttonIndex == 0) {
            
            
            [self.navigationController popViewControllerAnimated:YES];

            NSLog(@"1111111");
            
        }else if(buttonIndex == 1){
            
            
            ////NSLog(@"2222222");
            
            
        }
        
    }else {
        
    }
    
    
}


- (void)detectionVoice {
    
    [self.audioRecorder updateMeters];//刷新音量数据
    //获取音量的平均值  [recorder averagePowerForChannel:0];
    //音量的最大值  [recorder peakPowerForChannel:0];
    
    double lowPassResults = pow(10, (0.05 * [self.audioRecorder peakPowerForChannel:0]));
    //最大50  0
    //图片 小-》大
    if (0<lowPassResults<=0.06) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_01.png"]];
    }else if (0.06<lowPassResults<=0.13) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_02.png"]];
    }else if (0.13<lowPassResults<=0.20) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_03.png"]];
    }else if (0.20<lowPassResults<=0.27) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_04.png"]];
    }else if (0.27<lowPassResults<=0.34) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_05.png"]];
    }else if (0.34<lowPassResults<=0.41) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_06.png"]];
    }else if (0.41<lowPassResults<=0.48) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_07.png"]];
    }else if (0.48<lowPassResults<=0.55) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_08.png"]];
    }else if (0.55<lowPassResults<=0.62) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_09.png"]];
    }else if (0.62<lowPassResults<=0.69) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_10.png"]];
    }else if (0.69<lowPassResults<=0.76) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_11.png"]];
    }else if (0.76<lowPassResults<=0.83) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_12.png"]];
    }else if (0.83<lowPassResults<=0.9) {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_13.png"]];
    }else {
        [self.imageView_record setImage:[UIImage imageNamed:@"record_animate_14.png"]];
    }
}


#pragma mark - setter && getter

/**
 *  获得录音机对象
 *
 *  @return 录音机对象
 */
-(AVAudioRecorder *)audioRecorder{

    if (!_audioRecorder) {
        //创建录音文件保存路径
        NSURL *url=[self getSavePath];
        //创建录音格式设置
        NSDictionary *setting=[self getAudioSetting];
        //创建录音机
        NSError *error=nil;
        _audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate=self;
        _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES
        if (error) {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}

-(AVAudioPlayer *)audioPlayer{
    
    if (!_audioPlayer) {
        NSURL *url=[self getSavePath];
        NSError *error=nil;
        _audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
        _audioPlayer.numberOfLoops=0;
        [_audioPlayer prepareToPlay];
        if (error) {
            NSLog(@"创建播放器过程中发生错误，错误信息：%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioPlayer;
}


/**
 *  取得录音文件保存路径
 *
 *  @return 录音文件路径
 */
-(NSURL *)getSavePath {
    
    NSString *urlStr=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

    self.cafPath = urlStr ;
    self.strMp3Path = urlStr;
    
    NSURL *url=[NSURL fileURLWithPath:[urlStr stringByAppendingPathComponent:kRecordAudioFile]];
    
    return url;
}

/**
 *  取得录音文件设置
 *
 *  @return 录音设置
 */
-(NSDictionary *)getAudioSetting{

    NSDictionary *recordFileSettings = [NSDictionary
                                        dictionaryWithObjectsAndKeys:
                                        [NSNumber numberWithInt:AVAudioQualityMedium],
                                        AVEncoderAudioQualityKey,
                                        [NSNumber numberWithInt:16],
                                        AVEncoderBitRateKey,
                                        [NSNumber numberWithInt: 2],
                                        AVNumberOfChannelsKey,
                                        [NSNumber numberWithFloat:44100.0],
                                        AVSampleRateKey,
                                        nil];
    return recordFileSettings;
}


#pragma mark - 录音机代理方法
/**
 *  录音完成，录音完成后播放录音
 *
 *  @param recorder 录音机对象
 *  @param flag     是否成功
 */
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    
   NSLog(@"success");
    self.flag = YES;
}


- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
    
    NSLog(@"error");
    self.flag = NO;

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void) toMp3:(NSString*)cafFileName
{
    NSString *cafFilePath =[self.cafPath stringByAppendingPathComponent:cafFileName];
    
//    NSDateFormatter *fileNameFormat=[[NSDateFormatter alloc] init];
//    [fileNameFormat setDateFormat:@"yyyyMMddhhmmss"];
//    NSString *mp3FileName = [fileNameFormat stringFromDate:[NSDate date]];
    
    NSString *mp3FileName = @"record";
    mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];
  
    NSString *mp3FilePath = [self.strMp3Path stringByAppendingPathComponent:mp3FileName];
    
    @try {
        int read, write;
        
        FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");//被转换的文件
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");//转换后文件的存放位置
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 44100);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
             read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        
        NSLog(@"%@",[exception description]);
    }
    @finally {
     
        //
    }
    
}


- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.timer = nil;
}
//- (NSString *)getIPAddress {
//         NSString *address = @"error";
//          struct ifaddrs *interfaces = NULL;
//        struct ifaddrs *temp_addr = NULL;
//        int success = 0;
//        // retrieve the current interfaces - returns 0 on success
//        success = getifaddrs(&interfaces);
//        if (success == 0) {
//                // Loop through linked list of interfaces
//                temp_addr = interfaces;
//                while(temp_addr != NULL) {
//                        if(temp_addr->ifa_addr->sa_family == AF_INET) {
//                                // Check if interface is en0 which is the wifi connection on the iPhone
//                                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
//                                        // Get NSString from C String
//                                        address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
//                                    }
//                            }
//                        temp_addr = temp_addr->ifa_next;
//                    }
//            }
//        // Free memory
//        freeifaddrs(interfaces);
//        return address;
//}


@end
